package com.huaqin.excel.handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.huaqin.excel.beans.ContentBean;
import com.huaqin.excel.util.InternationalUtils;

/**
 * other file dir copy 
 * @author taojin
 *
 */
public class CommonFileHandler {
	
	private static CommonFileHandler instance = null;
	private String finalDirName = null;
	private String filePath = System.getProperty("user.dir");//get eclipse root path
	private String testResult = InternationalUtils.getStringFromProperties("Test_result");
	private String otherExtra = InternationalUtils.getStringFromProperties("Other_extra");
	private String backgroundPicture = InternationalUtils.getStringFromProperties("Huawei_Background_picture");
	private String waiverFilesDir = InternationalUtils.getStringFromProperties("Waiver_files");
	private String upgradeAndDriverTxt = InternationalUtils.getStringFromProperties("Upgrade_AND_Driver");
	
	private CommonFileHandler() {
	}
	
	/**sington instance
	 * @return
	 * @author guojianhui
	 */
	public static CommonFileHandler getInstance() {

		if (instance == null) {
			instance = new CommonFileHandler();
		}
		
		return instance;
	}
	
	/**
	 * gc free memory
	 */
	public void free() {
		instance = null;
//		System.gc();
	}
	

			
	public void dealExistFile(){
				
		ContentBean beans = ContentBean.getInstance();
		ExcelDataSource dataSource = new ExcelDataSource();
		
		ArrayList<String> selectFilePath = beans.getSelectFilesPath();//get select file path		
		ArrayList<String> selectFileName = beans.getSelectFilesName();//get select file name

		ArrayList<String> selectVideoPath = beans.getSelectVideoPath();//get select Video file path
		ArrayList<String> selectVideoName = beans.getSelectVideoName();//get select Video file name
		
		SimpleDateFormat dayinfo = new SimpleDateFormat("yyyy.MM.dd");//get the time of provider date
//		System.out.println(dayinfo.format(new Date()));
		
		ExcelDataHandler handler = ExcelDataHandler.getInstance();	
		
		String[] versionfirst = handler.getPropHashMap("ro.build.version.incremental").split("B");		
		String[] versionsecond = handler.getPropHashMap("ro.build.display.id").split("B");
		
		if(versionfirst[1].equals(versionsecond[1])){
			//judge and set different folder by display and huawei incremental version 
			finalDirName = handler.getPropHashMap("ro.product.name") + "_" + beans.getCountry()+ beans.getOperator()
					+ "_" + handler.getPropHashMap("ro.build.version.incremental");
			
		}else{
			finalDirName = handler.getPropHashMap("ro.product.name") + "_" + beans.getCountry()+ beans.getOperator()
					 + versionfirst[0] + "B" + versionsecond[1] + "_B" + versionfirst[1];
		}
		
		String newFileName = filePath + "/" + finalDirName;		
		String checklistFile = "Google_TA_Checklist-V3.3_" + dayinfo.format(new Date()) + ".xls";
		
		mkdirForDir(finalDirName);
		System.out.println("start copy public files...");
		copyFolder(filePath + "/publicFiles", newFileName + "/");//copy public folder
		//copy HUAWEI "waiguan" photo
		System.out.println("start copy HUAWEI files...");
		copyFolder(filePath + "/HUAWEI/" + handler.getPropHashMap("ro.product.name")+ "/",newFileName + "/" + otherExtra + "/");
		//copyFile(filePath + "/HUAWEI/" + handler.getPropHashMap("ro.product.name")+ "/" + backgroundPicture + ".jpg",newFileName + "/" + otherExtra + "/", backgroundPicture + ".jpg");
		//set and copy checklist
		System.out.println("start copy Google_TA_Checklist...");
		copyFile(filePath + "/" + "Google_TA_Checklist.xls",newFileName + "/" + testResult + "/", checklistFile);
		deleteFile(filePath + "/" + "Google_TA_Checklist.xls");
		copyFile(filePath + "/HUAWEI/" + upgradeAndDriverTxt + ".txt",newFileName + "/" + handler.getPropHashMap("ro.product.name") + handler.getPropHashMap("ro.build.version.incremental") + "/",upgradeAndDriverTxt + ".txt");
		copyFile(filePath + "/" + "df.txt",newFileName + "/", "df.txt");
		deleteFile(filePath + "/" + "df.txt");
		copyFile(filePath + "/" + "getprop.txt",newFileName + "/", "getprop.txt");
		deleteFile(filePath + "/" + "getprop.txt");
		copyFile(filePath + "/" + "AppInfo.txt",newFileName + "/", "AppInfo.txt");
		deleteFile(filePath + "/" + "AppInfo.txt");
		
		//copy select file
		for(int i=0;i<selectFilePath.size();i++){
			System.out.println("start copy upgradeAndDriver...");
			copyFile(selectFilePath.get(i),newFileName + "/" + handler.getPropHashMap("ro.product.name") + handler.getPropHashMap("ro.build.version.incremental") + "/",selectFileName.get(i));
//			System.out.println("taojin" + selectFilePath.get(i));
		}
		
		//copy select video file
		for(int i=0;i<selectVideoPath.size();i++){
			System.out.println("start copy boot video...");
			copyFile(selectVideoPath.get(i),newFileName + "/",selectVideoName.get(i));
//			System.out.println("taojin" + selectVideoPath.get(i));
		}

		if(dataSource.isInternalProduct(handler.getPropHashMap("ro.product.name")) != true) {
			copyFolder(getRootDirName() + "/HUAWEI/globallWaiveFiles", newFileName + "/" + getwaiverFilesDir());
		}else{
			copyFolder(getRootDirName() + "/HUAWEI/internalWaiveFiles", newFileName + "/" + getwaiverFilesDir());
		}
	}	
	
	public void mkdirForDir(String dirString) {

		File file = new File(dirString);
		if (!file.exists() && !file.isDirectory()) {
			file.mkdir();
		} else {
		}

	}
	
	/**
	 * @param oldPath
	 * @param newDirPath
	 * @param newFilePath
	 */
	public void copyFile(String oldPath, String newDirPath, String newFilePath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			
			  File dir = new File(newDirPath);

			 //  create a new directory, will do nothing if directory exists
			 if(dir != null /*&& dir.isDirectory() && dir.exists()*/) {
				 dir.mkdir();  
			 }   
			File newFile = new File(dir, newFilePath);
			if(newFile != null && !newFile.exists()) {
				try{
					newFile.createNewFile();
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
			if (oldfile.exists()) { 
				InputStream inStream = new FileInputStream(oldPath); 
				FileOutputStream fs = new FileOutputStream(newDirPath+newFilePath);
				byte[] buffer = new byte[1444];
				int length;
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; 
//					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();

		}

	}

	/**
	 * @param oldPath
	 * @param newPath
	 */
	public void copyFolder(String oldPath, String newPath) {

		try {
			(new File(newPath)).mkdirs();
			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}

				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(newPath
							+ "/" + (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
				if (temp.isDirectory()) {
					copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();

		}

	}
	
	public void deleteFile(String sPath) {
	    File file = new File(sPath);
	    // delete if the folder is null
	    if (file.isFile() && file.exists()) {
	        file.delete();
	    }

	}

	public String getfinalDirName() {

		return finalDirName;
	}

	public String getRootDirName() {

		return filePath;
	}
	
	public String gettestResult(){
		
		return testResult;
	}
	
	public String getotherExtra() {

		return otherExtra;
	}
	
	public String getbackgroundPicture(){
		
		return backgroundPicture;
	}
	
	public String getwaiverFilesDir() {

		return waiverFilesDir;
	}
	
	public String getUpgradeAndDriverTxt() {

		return upgradeAndDriverTxt;
	}
	
}
